<template>
    <!-- 个人资料区域开始 -->
    <div style="margin-top: 40px">
        <el-descriptions title="个人资料" direction="vertical" border style="margin: 10px 40px 0 40px;" :data="data.profile">
            <el-descriptions-item :rowspan="2" :width="140" label="头像" align="center">
                <div class="avatar-container">
                    <el-upload
                            class="avatar-uploader"
                            :action="`http://localhost:8000/api/${data.profile.user_id}/upload-profile-photo`"
                            :show-file-list="false"
                            :on-success="handleUploadSuccess"
                            :before-upload="beforeUpload"
                            :headers="getUploadHeaders()"
                    >  <!-- action:请求路径 单大括号插值 + v-bind（：的全称）动态绑定属性-->
                        <div class="avatar-wrapper" @mouseenter="showReplaceTip = true" @mouseleave="showReplaceTip = false">
                            <el-avatar :src="data.profile.profile_photo_path" :size="100" fit="cover" shape="circle" @error="errorHandler">
                                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载错误"/> <!--图片加载失败的回退行为-->
                            </el-avatar>
                            <div v-if="showReplaceTip" class="replace-tip">点击上传</div>
                        </div>
                    </el-upload>
                </div>
            </el-descriptions-item>
            <el-descriptions-item label="用户ID" :width="180">
                <template #default>
                    <span>{{ data.profile.user_id }}</span>
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="电话" prop="phone">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.phone }}</span>
                    <el-input v-else v-model="data.profile.phone" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称" prop="username">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.username }}</span>
                    <el-input v-else v-model="data.profile.username" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="电子邮件" prop="email">
                <template #default>
                    <span v-if="!data.isEditing">{{ data.profile.email }}</span>
                    <el-input v-else v-model="data.profile.email" />
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :width="180">
                <template #default>
                    <span>{{ data.profile.created_at }}</span>
                </template>
            </el-descriptions-item>
            <el-descriptions-item label="最近更新时间" style="right: 0">
                <template #default>
                    <span>{{ data.profile.updated_at }}</span>
                </template>
            </el-descriptions-item>
        </el-descriptions>
        <div style="display: flex; align-items: center; justify-content: center; margin-top: 10px">
            <el-button v-if="!data.isEditing" @click="data.isEditing = !data.isEditing" type="primary" style="width: 100px">
                编辑资料
            </el-button>
            <el-button v-else @click="updateProfile" type="primary" style="width: 100px">
                保存信息
            </el-button>
        </div>
    </div>
    <!-- 个人资料区域结束 -->

    <!--我的标签区域开始-->
    <div style="margin-top: 20px">
        <p style="margin: 40px 10px 0 40px">我的标签：</p>
        <!-- 标签列表 : 用户首次注册登录后进行选择、或后续进行添加-->
        <div style="margin: 20px 0 0 40px">
            <span v-if="data.profile.tags"><el-tag v-for="tag in data.profile.tags.split(',')" :key="tag" type="success" style="margin-right: 10px">{{ tag }}</el-tag></span>
            <span v-else>您暂未选择感兴趣的标签！</span>
            <el-button @click="dialogVisible = true" style="margin-left: 20px"><el-icon><Plus /></el-icon>&nbsp;&nbsp;添加感兴趣的标签</el-button>
        </div>
    </div>
    <!--我的标签区域结束-->

    <!-- 添加标签弹框开始 -->
    <el-dialog title="添加感兴趣的标签" v-model="dialogVisible" width="600px" destroy-on-close align-center>
        <p>选择现有标签添加（最多添加10个）</p>
        <!-- 现有标签列表 -->
        <div class="existing-tags">
            <h4>热门标签</h4>
            <el-tag
                v-for="tag in hotTags"
                :key="tag.tagId"
                :type="tag.isSelected ? 'success' : ''"
                @click="toggleTagSelection(tag)"
                style="margin-right: 8px; margin-top: 8px; cursor: pointer">
                {{ tag.tagName }}
            </el-tag>
        </div>
        <!-- 已选标签预览 -->
        <div v-if="selectedTags.length > 0" class="selected-preview">
            <h4>已选标签</h4>
            <el-tag
                v-for="tag in selectedTags"
                :key="tag.tagId || tag.tempId"
                type="success"
                closable
                @close="handleSelectedRemove(tag)"
            >
                {{ tag.tagName }}
            </el-tag>
        </div>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitTags">确认添加</el-button>
        </template>
    </el-dialog>
    <!-- 添加标签弹框结束 -->

    <!--修改密码 + 账号注销区域开始-->
    <div style="margin-top: 40px">
        <div v-if="data.editView" style="display: flex; align-items: center">
            <el-form ref="passwordRef" :model="data.password" :rules="data.rules" label-width="80px" style="display: flex; align-items: center; margin: 10px 20px 0">
                <el-form-item label="新密码" prop="newPassword">
                    <el-input  v-model="data.password.newPassword" show-password  style="width: 200px" placeholder="请输入新密码"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="data.password.confirmPassword" show-password  style="width: 200px" placeholder="确认新密码"/>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="submitForm" style="width: 100px">确定</el-button>
            <el-button @click="data.editView = false" style="width: 100px">取消</el-button>
        </div>
        <div v-else>
            <span style="margin-left: 40px">密码：</span>
            <el-button type="primary" link style="margin-left: 80%" @click="openEditView">修改密码</el-button>
        </div>
    </div>
    <!--修改密码区域结束-->

    <!-- 账号注销开始 -->
    <div style="margin-top: 20px">
        <div style="margin-top: 40px">
            <span style="margin-left: 40px">账号注销：</span>
            <el-button type="primary" link style="margin-left: 80%" @click="deleteView">注销</el-button>
        </div>
    </div>
    <!-- 账号注销结束 -->
</template>

<script setup>
import { reactive, ref, computed, watch} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import { markRaw } from 'vue'
import {Delete, Plus} from "@element-plus/icons-vue";

const showReplaceTip = ref(false); // 鼠标悬停上传字段展示控制
const errorHandler = () => true //图片加载失败的回退行为

let user;
//获取本地存储中的用户信息
let loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}
let token = '';
const getUploadHeaders = () => {
    const user = JSON.parse(localStorage.getItem('code_user') || '{}');
    token = user.token;
    if (token) {
        return {
            'token': `${token}`
        };
    }
    return {};
};

const data = reactive({
    isEditing: false,
    editView: false,
    password: {
        newPassword: '',
        confirmPassword: ''
    },
    profile: {
        profile_photo_path: user?.profile_photo_path || '',
        user_id: user?.user_id || '',
        username: user?.username || '',
        password: user?.password || '',
        phone: user?.phone || '',
        email: user?.email || '',
        role_id: user?.role_id || undefined,
        tags: user?.tags || '',
        created_at: user?.created_at || undefined,
        updated_at: user?.updated_at || undefined,
        role: {
            role_id: user?.role_id || undefined,
            roleName: user?.role.roleName || '',
            description: user?.role.description || '',
        },
    },
    rules: {
        newPassword: [
            { required: true, message: '请输入最新密码', trigger: 'blur' },
            {min: 6, message: '最少输入6位', trigger: 'blur'},
        ],
        confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            {min: 6, message: '最少输入6位', trigger: 'blur'},
        ],
    },
})

const handleUploadSuccess = (response) => {
    data.profile.updated_at = currentTime;
    if (response.code === "200") {
        data.profile.profile_photo_path = response.data.profile_photo_path;// 更新 data.profile.profile_photo_path
        data.profile.token = token; // 保留 token
        localStorage.setItem('code_user', JSON.stringify(data.profile));// 更新本地存储图片
        ElMessage.success("上传成功")
        location.reload(); // 刷新页面
    } else {
        ElMessage.error(response.msg)
    }
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';  // 更通用的图片类型校验
    const isLt2M = file.size / 1024 / 1024 < 2;  // 限制文件大小不超过2MB
    if (!isJpgOrPng) {
        ElMessage.error('只能上传图片文件（JPEG/PNG/JPG等）');
    }
    if (!isLt2M) {
        ElMessage.error('文件大小不能超过2MB');
    }
    return isJpgOrPng && isLt2M;
};


//保存数据到后端的逻辑
const updateProfile = () => {
    data.profile.updated_at = currentTime;
    request.post('/api/updateprofile', data.profile,).then(res => {
        if (res.code === '200') {
            ElMessage.success('保存成功')
            data.profile.token = token; // 保留 token
            localStorage.setItem('code_user', JSON.stringify(data.profile));// 更新本地存储数据
            location.reload(); // 刷新页面
        } else {
            ElMessage.error('保存失败')
        }
    })
    data.isEditing = false;
};



const passwordRef = ref();
const openEditView =  () => {
    data.editView = true;
}
// 表单验证和提交数据到后端的逻辑
const submitForm = () => {
    passwordRef.value.validate((valid) => {  // 触发表单验证
        if (valid) {
            if (data.password.newPassword === data.password.confirmPassword) {
                request.post('/api/updatepassword' ,data.password.newPassword,{
                    params: { user_id: data.profile.user_id }
                }).then(res => {
                    if (res.code === '200') {
                        ElMessage.success("密码更新成功")
                        data.profile.password = data.password.newPassword; // 更新profile数据
                        data.profile.updated_at = currentTime;
                        localStorage.setItem('code_user', JSON.stringify(data.profile));// 更新本地存储数据
                        location.reload(); // 刷新页面
                        data.editView = false;
                    } else {
                        ElMessage.error('密码更新失败');
                    }
                }).catch((error) => {
                    ElMessage.error('请求出错：' + error.message);
                });
            } else {
                ElMessage.error("两次密码不一致, 请确认密码")
            }
        }
    })
};


//当前时间处理
const currentTime = ref(''); // 使用 ref 定义一个响应式变量来存储当前时间
const updateTime = () => {  // 在组件挂载时获取当前时间并格式化
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 调用函数获取并设置初始时间
updateTime();


//删除单个用户点击事件
const deleteView = () => {
    ElMessageBox.confirm('您确定要注销账户嘛！ 此操作不可逆转！请谨慎操作！', '账户注销确认', {type: 'warning', icon: markRaw(Delete),}).then(res => {
        request.delete('/api/admin/delete/' + data.profile.user_id).then(res => {
            if (res.code === '200') {
                ElMessage.success("账户注销成功")
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {

    })
}



// 添加标签
const dialogVisible = ref(false);  // 状态管理
const hotTags = ref([]); // 从后端获取的热门标签
const selectedTags = ref([]); // 已选标签（包含现有标签和自定义标签）

// 初始化：打开对话框时加载热门标签
watch(() => dialogVisible.value, (newVal) => {
    if (newVal) {
        fetchHotTags();
        resetState(); // 重置选择状态
    }
});

// 获取热门标签
const fetchHotTags = async () => {
    try {
        const res = await request.get('/api/cata/selectTagAll');
        if (res.code === '200') {
            hotTags.value = res.data.map(tag => ({
                ...tag,
                isSelected: false // 添加选中状态标记
            }));
        }
    } catch (error) {
        ElMessage.error('加载标签失败');
    }
};

// 切换现有标签选中状态
const toggleTagSelection = (tag) => {
    // 先更新标签的选中状态
    tag.isSelected = !tag.isSelected;

    if (tag.isSelected) {
        // 如果是选中状态，则添加到已选标签列表
        selectedTags.value = [...selectedTags.value, tag];
    } else {
        // 如果是取消选中状态，则从已选标签列表中移除
        selectedTags.value = selectedTags.value.filter(t => t.tagId !== tag.tagId);
    }

    console.log("当前已选标签:", selectedTags.value);
};


// 移除已选标签
const handleSelectedRemove = (tag) => {
    if (tag.tagId) {
        // 现有标签：恢复热门标签的选中状态
        hotTags.value = hotTags.value.map(t =>
            t.tagId === tag.tagId ? { ...t, isSelected: false } : t
        );
    }
    selectedTags.value = selectedTags.value.filter(t => t !== tag);
};

// 提交标签到后端
const submitTags = async () => {
    if (selectedTags.value.length === 0) {
        ElMessage.warning('请至少选择1个标签');
        return;
    }
    try {
        // 整理标签名称为逗号分隔的字符串（如"前端技术,后端开发"）
        const tagNames = selectedTags.value.map(tag => tag.tagName).join(',');
        const res = await request.post('/api/users/addUserTags',{
            user_id: data.profile.user_id,
            tags: tagNames
        });
        if (res.code === '200') {
            ElMessage.success('标签添加成功');
            data.profile.tags = tagNames // 更新标签数据
            data.profile.token = token; // 保留 token
            localStorage.setItem('code_user', JSON.stringify(data.profile));// 更新本地存储数据
            location.reload(); // 刷新页面
            dialogVisible.value = false;
        } else {
            ElMessage.error(res.msg || '标签添加失败');
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试');
    }
};

// 重置状态
const resetState = () => {
    selectedTags.value = [];
    hotTags.value.forEach(tag => tag.isSelected = false);
};
</script>


<style>
.avatar-uploader {
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    border-radius: 50%;
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}


.avatar-container {
    position: relative;
}

.avatar-wrapper {
    position: relative;
    width: 100px; /* 可根据需要调整头像大小 */
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.replace-tip {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.avatar-wrapper:hover .replace-tip {
    opacity: 1;
}
</style>